<template>
  <div class="list-setting-container">
    <el-tabs v-model="curTabIndex" type="card" class="tab-content">
      <el-tab-pane name="0">
        <span slot="label"><el-badge :is-dot="listStatus || filterStatus">列表及筛选配置</el-badge></span>
      </el-tab-pane>
      <el-tab-pane name="1">
        <span slot="label"><el-badge :is-dot="exportStatus">导出字段配置</el-badge></span>
      </el-tab-pane>
      <el-tab-pane name="2">
        <span slot="label"><el-badge :is-dot="cardStatus">卡片视图配置</el-badge></span>
      </el-tab-pane>
    </el-tabs>
    <div v-show="curTabIndex === '0'">
      <SectionTitle :is-dot="listStatus" title="列表字段配置">
        <InfoIcon content="至少勾选一项" />
        <span class="title-tip">(勾选需要展示的字段，拖动字段进行排序)</span>
        <div class="fields-checkbox">
          <el-checkbox v-model="listFieldsSelectAllStatus" @change="listFieldsSelectAllChange">
            <span :style="{fontWeight: listFieldsSelectAllStatus ? 'bold' : ''}" style="color: #333; font-size: 14px">全选</span>
          </el-checkbox>
        </div>
      </SectionTitle>
      <SettingGraggable v-if="listFields.length" ref="listSettingRef" v-model="listFields" @getCurSelectedNum="getCurSelectedNum" />
      <EmptyPlaceholder v-else :empty-text-top="0" text="暂无可配置字段" style="width: 300px" />
      <SectionTitle :is-dot="filterStatus" title="筛选项配置" style="margin-top: 20px">
        <InfoIcon content="至少勾选一项" />
        <span class="title-tip">(勾选需要配置的字段筛选项)</span>
        <div class="fields-checkbox">
          <el-checkbox v-model="filterFieldsSelectAllStatus" @change="filterFieldsSelectAllChange">
            <span :style="{fontWeight: filterFieldsSelectAllStatus ? 'bold' : ''}" style="color: #333; font-size: 14px">全选</span>
          </el-checkbox>
        </div>
      </SectionTitle>
      <FilterSetting v-if="configFields.length" ref="filterSettingRef" v-model="configFields" @checkboxChange="filterChange" @updateComponent="updateComponent" />
      <EmptyPlaceholder v-else :empty-text-top="0" text="暂无可配置字段" style="width: 300px" />
    </div>
    <!-- 导出配置字段 -->
    <ExportSetting
      v-show="curTabIndex === '1'"
      ref="exportSettingRef"
      :form-list="formList"
      @statusCheck="$emit('statusCheck')"
      @updateExportDot="updateExportDot" />
    <!-- 卡片视图配置 -->
    <CardSetting
      v-show="curTabIndex === '2'"
      ref="cardSettingRef"
      v-model="card.configs"
      :form-list="formList"
      @statusCheck="$emit('statusCheck')"
      @updateCardDot="updateCardDot"
    />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import SettingGraggable from './settingGraggable';
import FilterSetting from './filterSetting';
import ExportSetting from './exportSetting';
import CardSetting from './cardSetting';
import { EventBus } from '@/utils/eventBus';
import { forEachFormOptions } from '@/utils/formMakeUtils.js';
import { listFieldTargets, dataFieldTargets } from './settingTargets';

export default {
  name: 'ListSetting',
  components: {
    SectionTitle,
    EmptyPlaceholder,
    FilterSetting,
    SettingGraggable,
    ExportSetting,
    CardSetting
  },
  props: {
    configFields: {
      type: Array,
      default: () => []
    },
    formList: {
      type: Array,
      default: () => []
    },
    list: {
      type: Object,
      default: () => ({})
    },
    card: {
      type: Object,
      default: () => ({
        fields: [],
        configs: {
          width: '400',
          minWidth: '',
          maxWidth: '',
          height: '',
          minHeight: '',
          maxHeight: '',
          options: [],
          isEnable: false
        }
      })
    }
  },
  data() {
    return {
      listStatus: false,
      filterStatus: false,
      exportStatus: false,
      cardStatus: false,
      curTabIndex: '0',
      listFields: [
        { key: 'currentNode', name: '当前节点' },
        { key: 'currentHandler', name: '当前处理人' },
        { key: 'status', name: '状态' }
      ],
      initFields: ['currentNode', 'currentHandler', 'status'],
      filterFieldsSelectAllStatus: false
    };
  },
  computed: {
    listFieldsSelectAllStatus: {
      get() {
        return this.listFields.every(field => field.isShow);
      },
      set(val) {
        this.$forceUpdate();
      }
    }
  },
  watch: {
    configFields: {
      handler(list) {
        this.filterFieldsSelectAllStatus = list.every(field => field.isFilter);
      },
      deep: true
    },
    list: {
      handler: function(val) {
        this.initCheck(val);
      }
    }
  },
  created() {
    EventBus.$on('formOptionsChange', configObj => {
      this.formListChange(this.formList);
    });
    this.statusCheck();
  },
  methods: {
    statusCheck() {
      const listSelectNum = this.listFields.reduce((pre, curr) => pre + (curr['isShow'] ? 1 : 0), 0);
      const filterSelectNum = this.configFields.reduce((pre, curr) => pre + (curr['isFilter'] ? 1 : 0), 0);
      this.listStatus = listSelectNum < 1;
      this.filterStatus = filterSelectNum < 1;
    },
    initCheck(list) {
      this.listStatus = list.field.filter(it => it.isCheck).length < 1;
      this.filterStatus = list.filter.filter(it => it.isCheck).length < 1;
    },
    // 初始化列表字段，引用时会调用
    initList(formList) {
      this.$set(this, 'listFields', this.getList(_.cloneDeep(formList)));
    },
    getCurSelectedNum(num) {
      this.listStatus = num < 1;
      this.$emit('statusCheck');
    },
    listFieldsSelectAllChange(status) {
      this.listFields.forEach(field => {
        this.$set(field, 'isShow', status);
      });
      this.$refs['listSettingRef'].onCheckboxChange();
    },
    filterFieldsSelectAllChange(status) {
      this.configFields.forEach(field => {
        this.$set(field, 'isFilter', status);
      });
      this.$refs['filterSettingRef'].updateComponent();
    },
    updateComponent(num) {
      this.filterStatus = num < 1;
      this.$emit('statusCheck');
    },
    updateExportDot(status) {
      this.exportStatus = status;
    },
    updateCardDot(status) {
      this.cardStatus = status;
    },
    filterChange() {
      this.$nextTick(() => {
        this.filterFieldsSelectAllStatus = this.configFields.every(field => field.isFilter);
      });
    },
    formListChange: _.debounce(function(formList) {
      let oldListFields = _.cloneDeep(this.listFields);
      const newListFields = this.getList(_.cloneDeep(formList));
      const deletedArr = _.differenceBy(oldListFields, newListFields, 'key');
      const addArr = _.differenceBy(newListFields, oldListFields, 'key');

      if (deletedArr.length) {
        // 删除
        _.pullAllBy(oldListFields, deletedArr, 'key');
      }
      if (addArr.length) {
        // 添加
        oldListFields = _.concat(oldListFields, addArr);
      }
      // 修改名称
      oldListFields.forEach(i => {
        const temp = newListFields.find(j => j.key === i.key);
        if (temp) {
          i.subformFullName = temp.subformFullName;
          i.name = temp.name;
          i.type = temp.type;
        }
      });
      this.$set(this, 'listFields', oldListFields);
    }, 200),
    getList(formList) {
      const listFieldTemp = [
        { key: 'currentNode', name: '当前节点' },
        { key: 'currentHandler', name: '当前处理人' },
        { key: 'status', name: '状态' }
      ];
      forEachFormOptions(formList, item => {
        if (listFieldTargets.includes(item.type)) {
          if (item.type === 'subform') {
            if (Array.isArray(item.subform) && item.subform.length) {
              item.subform.forEach(i => {
                if (dataFieldTargets.includes(i.type)) {
                  i.subformFullName = item.name + '.' + i.name;
                }
              });
              listFieldTemp.push(...item.subform.filter(i => dataFieldTargets.includes(i.type)));
            }
          } else {
            listFieldTemp.push(item);
          }
        }
      }, { notForEachSubform: true });
      return listFieldTemp;
    },
    validate() {
      const listSelectNum = this.listFields.reduce((pre, curr) => pre + (curr['isShow'] ? 1 : 0), 0);
      const filterSelectNum = this.configFields.reduce((pre, curr) => pre + (curr['isFilter'] ? 1 : 0), 0);
      const result = !(listSelectNum > 0 && filterSelectNum > 0);
      return result;
    },
    // 列表字段和筛选配置都至少需要勾选一项
    validateForm() {
      return new Promise((resolve, reject) => {
        // 列表字段配置项勾选数量
        const listSelectNum = this.listFields.reduce((pre, curr) => pre + (curr['isShow'] ? 1 : 0), 0);
        if (listSelectNum < 1) {
          reject('请勾选高级设置-列表字段配置');
          return;
        }
        // 筛选项配置项勾选数量
        const filterSelectNum = this.configFields.reduce((pre, curr) => pre + (curr['isFilter'] ? 1 : 0), 0);
        if (filterSelectNum < 1) {
          reject('请勾选高级设置-筛选项配置');
          return;
        }
        resolve(true);
      });
    },
    getData() {
      const params = {};
      params.field = this.listFields.map(field => {
        return { key: field.key, name: field.name, subformFullName: field.subformFullName, isCheck: !!field.isShow };
      });
      params.filter = this.configFields.map(field => {
        return { key: field.key, name: field.name, isCheck: !!field.isFilter };
      });
      return params;
    },
    // 设置列表&筛选配置字段
    setData(data) {
      const { field, filter } = data;
      if (Array.isArray(field) && field.length) {
        this.listFields = field.map(item => {
          item.isShow = !!item.isCheck;
          delete item.isCheck;
          return item;
        });
      }
      if (Array.isArray(filter) && filter.length) {
        const filterCheckedStatus = {};
        filter.forEach(item => {
          filterCheckedStatus[item.key] = !!item.isCheck;
        });
        this.configFields.forEach((item, index) => {
          this.$set(item, 'isFilter', !!filterCheckedStatus[item.key]);
        });
        /* this.$nextTick(() => {
          this.configFields.forEach((item, index) => {
            this.$set(item, 'isFilter', !!filterCheckedStatus[item.key]);
          });
        }); */
      }
    }
  }
};
</script>

<style scoped lang="scss">
.list-setting-container {
  .tab-content {
    margin-bottom: 12px;
    &::v-deep {
      .el-tabs__header  {
        margin-bottom: 0 !important;
        border-bottom: 1px solid #ddd;
        .el-tabs__nav {
          border: none !important;
        }
        .el-tabs__item {
          padding: 0 12px !important;
          height: 32px !important;
          line-height: 32px !important;
          margin-right: 8px;
          border: 1px solid #ddd;
          border-radius: 4px 4px 0px 0px;
          color: #333;
          background: #f7f8fa;
          font-size: 16px;
          &:last-child {
            margin-right: 0px;
          }
          &.is-active {
            border-bottom-color: #FFFFFF !important;
            font-weight: bold;
            background: #fff;
            color: #406eff;
          }
        }
      }
      .el-badge {
        transform: translateY(-2px);
        .is-dot {
          top: 8px;
        }
      }
    }
  }
  .title-tip {
    font-size: 14px;
    color: #999;
    font-weight: normal;
    margin-left: 6px;
  }
  .el-icon-info{
    margin-left: 2px;
  }
  .el-icon-info:hover {
    color: #406EFF;
  }
  .fields-checkbox {
    margin-left: 6px;
    & ::v-deep {
      .el-checkbox__label {
        font-size: 12px;
        padding-left: 4px;
      }
      .el-checkbox {
        color: #333;
      }
    }
  }
}
</style>
